package logic

import (
	"context"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"yangming-college/app/usercenter/cmd/v1/model"
	"yangming-college/app/usercenter/cmd/v1/rpc/internal/svc"
	"yangming-college/app/usercenter/cmd/v1/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCasPathLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCasPathLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCasPathLogic {
	return &AddCasPathLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCasPathLogic) AddCasPath(in *pb.AddCasPathReq) (*pb.AddCasPathResp, error) {
	casbinPath := model.CasbinPath{
		Path:        in.Path.Path,
		Method:      in.Path.Method,
		Description: in.Path.Description,
	}
	// 1、检查path是否存在
	err := l.svcCtx.DB.Table("casbin_path").Where("path = ? and method = ?", in.Path.Path, in.Path.Method).First(&casbinPath).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// 2、添加url
			err := l.svcCtx.DB.Table("casbin_path").Create(&casbinPath).Error
			if err != nil {
				return nil, errors.Wrapf(err, "添加casbinPath失败")
			}
			return &pb.AddCasPathResp{}, nil
		}
		return nil, errors.Wrapf(err, "添加casbinPath失败")
	}

	return nil, errors.Wrapf(err, "casbinPath已存在")
}
